package com.vladmr.sleepytimepicker;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

public class AlarmReceiver extends BroadcastReceiver {
	private static final String TAG = "sleepytimepicker";
	private static final int NOTIFICATION_ID = 1;
	private Uri alertUri;
	private Context context;

	private String str_message = "";

	@Override
	public void onReceive(Context context, Intent intent) {
		this.context = context;
		str_message = intent.getStringExtra("message");
		// reminder that it is time to go to sleep
		try {
			// alertUri =
			// RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
			// if (alertUri == null) {
			alertUri = RingtoneManager
					.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
			// if notification is null
			if (alertUri == null) {
				alertUri = RingtoneManager
						.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
			}
			// }

			if (alertUri != null) {
				ShowNotification();
			}
		} catch (Exception e) {
			Log.e(TAG, "AlarmReceiver " + e.getMessage());
		}
	}

	private void ShowNotification() {
		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager mNotificationManager = (NotificationManager) context
				.getSystemService(ns);
		int icon = R.drawable.ic_launcher;
		long when = System.currentTimeMillis();
		CharSequence tickerText = str_message;
		CharSequence contentTitle = "My notification";
		CharSequence contentText = str_message;

		Intent notificationIntent = new Intent(context,
				ChooseFallasleepActivity.class);
		PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
				notificationIntent, Notification.FLAG_AUTO_CANCEL);
		if (android.os.Build.VERSION.SDK_INT >= 11) {
			 Notification.Builder builder = new Notification.Builder(context);
			 builder.setContentIntent(contentIntent).setSound(alertUri)
			 .setSmallIcon(icon).setTicker(tickerText).setWhen(when)
			 .setContentTitle(contentTitle).setContentText(contentText);
			
			 Notification notification = builder.getNotification();
			 mNotificationManager.notify(NOTIFICATION_ID, notification);
		} else {
			NotificationCompat.Builder builder = new NotificationCompat.Builder(
					context);
			builder.setContentIntent(contentIntent).setSound(alertUri)
					.setSmallIcon(icon).setTicker(tickerText).setWhen(when)
					.setContentTitle(contentTitle).setContentText(contentText);

			Notification notification = builder.getNotification();
			mNotificationManager.notify(NOTIFICATION_ID, notification);
		}
	}
}
